// 序列化二叉树
var serialize = function (root) {
  if (!root) return [];
  let res = [];
  let queue = [root];
  while (queue.length > 0) {
    let node = queue.shift();
    if (node !== null) {
      res.push(node.val);
      queue.push(node.left);
      queue.push(node.right);
    } else {
      res.push(null);
    }
  }
  return res;
};

// 反序列化主要思想就是按照层次遍历的顺序依次恢复父节点和子节点
var deserialize = function (data) {
  if (data.length === 0) return null;
  let root = new TreeNode(data.shift());
  let queue = [root];
  while (queue.length > 0) {
    let node = queue.shift();
    let left = data.shift();
    let right = data.shift();
    node.left = left == null ? null : new TreeNode(left);
    node.right = right == null ? null : new TreeNode(right);
    if (node.left) queue.push(node.left);
    if (node.right) queue.push(node.right);
  }
  return root;
};
